package com.dodo.blog;

import com.dodo.blog.ui.message.Message;
import com.google.inject.Injector;

import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class RequestCycle
        implements Serializable
{
    private static final long serialVersionUID = 1L;

    private static final ThreadLocal<RequestCycle> current = new ThreadLocal<RequestCycle>();

    private HttpServletRequest request;

    private HttpServletResponse response;

    private List<Message> messages = new ArrayList<Message>();

    private WebApplication webApplication;

    private FilterConfig config;

    private RequestCycle( HttpServletRequest request, HttpServletResponse response, WebApplication webApplication, FilterConfig config )
    {
        this.request = request;
        this.response = response;
        this.webApplication = webApplication;
        this.config = config;
    }

    public static void set( HttpServletRequest request, HttpServletResponse response, WebApplication webApplication, FilterConfig config )
    {
        current.set( new RequestCycle( request, response, webApplication, config ) );
    }

    public static RequestCycle get()
    {
        return current.get();
    }

    public HttpServletRequest getRequest()
    {
        return request;
    }

    public HttpSession getSession()
    {
        return request.getSession();
    }

    public String getParameter( String name )
    {
        return request.getParameter( name );
    }

    public HttpServletResponse getResponse()
    {
        return response;
    }

    public WebApplication getWebApplication()
    {
        return webApplication;
    }

    public void addMessage( Message message )
    {
        messages.add( message );
    }

    public void addMessages( Collection<Message> messages )
    {
        this.messages.addAll( messages );
    }

    public List<Message> getMessages()
    {
        return messages;
    }

    public Injector getInjector()
    {
        return ( Injector ) config.getServletContext().getAttribute( Injector.class.getName() );
    }
}
